<?php
/**
 * 我的钱包
 * User: zal
 * Date: 2016/2/28
 * Time: 11:52
 */
namespace Api\Controller;
use Api\Controller\BaseController;

class UserMoneyController extends BaseController {

    //钱包页面类型
    const REPAIR_MONEY         =   1;      // 维修金
    const REPAIR_BOND       =   2;      // 维修保证金
    const REPAIR_FOENUS       =   3;      // 维修金利息

    //资金类型
    const FLAG_MONEY         =   1;      // 金额（维修金或装修金）
    const FLAG_BOND       =   2;      // 保证金
    const FLAG_FOENUS       =   3;      // 利息

    //加载配置项
    // public function __construct() {
    //    parent::_initialize();
    //}

    public function index(){
        $data=array();
        $user_id=I('get.user_id','');
        $userData=$this->checkUserIsExist($user_id);
        if(isset($userData["code"])){
            $this->ajaxReturn($userData,'JSON');
        }
        //$users=$userData["user"];
        // $total=$users["total"];//用户余额

        $userMoney=$this->getUserMoney($user_id);

        if(isset($userMoney["code"])){
            $this->ajaxReturn($userMoney,'JSON');
            return;
        }else{
            $data["data"]=$userMoney;
            $data["code"]=200;
            $data["msg"]='ok';
        }
        $this->ajaxReturn($data,'JSON');
    }

    /**
     * 查看维修金额相关的页面（get请求的参数type说明 1.维修金 2.维修保证金 3.维修金利息）
     * return json
     */
    public function getMoenyIndex(){
        $year_foenus=0; //当是利息页面时调用
        $flag=0;
        $data=$moneyData=array();
        $type=I('type'); //类型 1维修 2装修 3商城
        $user_id=I('user_id','');
        $moneyType=I('flag',''); //页面类型（1.维修金 2.维修保证金 3.维修金利息）
        $pageSize = I('pageSize',3); //每页条数
        $pageIndex = I('pageIndex',1); //当前页
        $userData=$this->checkParams($user_id,$moneyType);
        if(isset($userData["code"])){
            $this->ajaxReturn($userData,'JSON');
        }
        $userMoney=$this->getUserMoney($user_id);
        if(isset($userMoney["code"])){
            $this->ajaxReturn($userMoney,'JSON');
        }
        //当前维修金
        if($moneyType==self::REPAIR_MONEY){
            $flag=self::FLAG_MONEY;
            $moneyData["money"]=$userMoney["repair_money"];
        }else if($moneyType==self::REPAIR_BOND){ //当前维修保证金
            $flag=self::FLAG_BOND;
            $moneyData["money"]=$userMoney["repair_bond"];
        }else if($moneyType==self::REPAIR_FOENUS){ //当前维修利息
            parent::_initialize();
            $year_foenus=C("site_interest");//利息年化率
            $flag=self::FLAG_FOENUS;
            $moneyData["year_foenus"]=($year_foenus*100)."%";
            $moneyData["money"]=$userMoney["repair_bond"];
        }else if($moneyType == 5){
            $flag = 5;
        }

        $mhMap["user_id"]=$user_id;
        $mhMap["type"]=$type;  //资金来源 4维修 3商城 2装修 1提现
        $mhMap["flag"]=$flag; //资金类别 1金额（维修金或装修金）2保证金 3利息 4小费 5余额 6退款
        $mhMap["is_plus"]=1;  //是增加还是减少
        $total=M("MoneyHistory")->where($mhMap)->sum('total');//历史累计收益

        //当日金额
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $mhMap['add_time']  = array('between',array($beginToday,$endToday));
        $today_total=M("MoneyHistory")->where($mhMap)->sum('total');//当日维修金

        //当月账单
        $beginThisMonth=mktime(0,0,0,date('m'),1,date('Y'));
        $endThisMonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
        $mhMap['add_time']  = array('between',array($beginThisMonth,$endThisMonth));
        unset($mhMap['is_plus']);

        $monthMoneyList=$this->selectMonthMoneyList($mhMap,$pageSize,$pageIndex);

        $moneyData["money_month"]=$monthMoneyList['list'];//当月账单
        $moneyData["money_his"]=empty($total)?"0":$total;;//历史累计收益
        $moneyData["money_today"]=empty($today_total)?"0":$today_total;//当日金额
        $moneyData["pages"]= $monthMoneyList['pages'];

        $data["data"]=$moneyData;
        $data["code"]=200;
        $data["msg"]='ok';
        $this->ajaxReturn($data,'JSON');;
    }

    /**
     * 月账单列表
     */
    public function getMonthMoneyList(){
        $flag=0;
        $data=$moneyData=array();
        $type=I('get.type','1'); //类型 1维修 2装修 3商城
        $user_id=I('get.user_id','');
        $moneyType=I('get.flag',''); //页面类型（1.维修金 2.维修保证金 3.维修金利息）
        $month=I('get.month',date('m')); //月份
        $year=I('get.year',date('Y')); //年份
        $page=I('get.page','1'); //页码
        $size=I('get.size','10'); //显示数目

        $userData=$this->checkParams($user_id,$moneyType);
        if(isset($userData["code"])){
            $this->ajaxReturn($userData,'JSON');
        }

        $userMoney=$this->getUserMoney($user_id);
        if(isset($userMoney["code"])){
            $this->ajaxReturn($userMoney,'JSON');
        }
        //当前维修金
        if($moneyType==self::REPAIR_MONEY){
            $flag=self::FLAG_MONEY;
        }else if($moneyType==self::REPAIR_BOND){ //当前维修保证金
            $flag=self::FLAG_BOND;
        }else if($moneyType==self::REPAIR_FOENUS){ //当前维修利息
            $flag=self::FLAG_FOENUS;
        }

        $day=$this->getMonthToDays($year,$month);
        $beginThisMonth=mktime(0,0,0,intval($month),1,intval($year));
        $endThisMonth=mktime(23,59,59,intval($month),intval($day),intval($year));
        $mhMap["user_id"]=$user_id;
        $mhMap["type"]=$type;  //资金来源 1维修 2装修 3商城
        $mhMap["flag"]=$flag; //资金类别 1金额（维修金或装修金）2保证金 3利息
        //$mhMap["is_plus"]=1;  //是增加还是减少
        $mhMap['add_time']  = array('between',array($beginThisMonth,$endThisMonth));
        $monthMoneyList=$this->selectMonthMoneyList($mhMap,$size,$page);
        $mhMap["is_plus"]=1;  //收入
        $month_total=M("MoneyHistory")->where($mhMap)->sum('total');//当月收入金额
        $moneyData["money_month"]=$monthMoneyList;//当月账单
        $moneyData["year"]=$year;//当月账单
        $moneyData["month"]=$month;//当月账单
        //$moneyData["money_out"]=empty($total)?"0":$total;;//历史累计收益
        $moneyData["money_in"]=$month_total;//当月收入
        $data["data"]=$moneyData;
        $data["code"]=200;
        $data["msg"]='ok';
        $this->ajaxReturn($data,'JSON');;
    }

    /**
     * 账单明细
     */
    public function getMoneyDetail(){
        $data=$moneyData=array();
        $user_id=I('get.user_id','');
        $moneyType=I('get.flag',''); //页面类型（1.维修金 2.维修保证金 3.维修金利息）
        $id=I('get.id','');
        if(empty($id)){
            $data["code"]=1001;
            $data["msg"]='缺少参数';
            $this->ajaxReturn($data,'JSON');
        }
        $userData=$this->checkParams($user_id,$moneyType);

        if(isset($userData["code"])){
            $this->ajaxReturn($userData,'JSON');
        }
        $moneyHistory=M('MoneyHistory')->where("id=".$id)->find();
        if(empty($moneyHistory)){
            $data["code"]=1001;
            $data["msg"]='没有该条明细记录';
            $this->ajaxReturn($data,'JSON');
        }
        $isPlus=$moneyHistory["is_plus"];
        $symbol="+";
        //是收入还是支出
        if($isPlus==0){
            $symbol="-";
        }
        $order_id=$moneyHistory["order_id"];
        $type=$moneyHistory["type"];
        $order_num="";
        if(!empty($order_id)){
            //查询维修订单
            if($type==1){
                $repairOrder=M('RepairOrder')->where("repair_order_id=".$order_id)->find();
                if(!empty($repairOrder)){
                    $order_num=$repairOrder["repair_order_num_alias"];
                }
            }else if($type==2){//查询装修订单
                $renovationOrder=M('RenovationOrder')->where("renovation_order_id=".$id)->find();
                if(!empty($renovationOrder)){
                    $order_num=$renovationOrder["renovation_order_num_alias"];
                }
            }else if($type==3){//查询商城订单

            }
        }
        $moneyData["type"]=$type;
        $moneyData["order_id"]=$order_id;
        $moneyData["order_num"]=$order_num;
        $moneyData["total"]=$symbol.$moneyHistory["total"];
        $moneyData["addtime"]=date("Y-m-d H:i:s",$moneyHistory["add_time"]);
        $moneyData["remark"]=$symbol.$moneyHistory["remark"];
        $data["data"]=$moneyData;
        $data["code"]=200;
        $data["msg"]='ok';
        $this->ajaxReturn($data,'JSON');;

    }


    private function checkParams($user_id,$moneyType){
        $data=array();
        $userData=$this->checkUserIsExist($user_id);
        if(isset($userData["code"])){
            return $userData;
        }
        if(empty($moneyType)){
            $data["code"]=1001;
            $data["msg"]='缺少参数';
            return $data;
        }else{
            return $userData;
        }
    }

    private function getDate($datetime){
        $str="";
        $startdate=mktime(0,0,0,date('m',$datetime),date('d',$datetime),date('Y',$datetime));
        $enddate=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $days=round(($enddate-$startdate)/3600/24) ;
        if($days==0){
            $str="今天";
        }else if($days==1){
            $str="昨天";
        }else if($days==2){
            $str="前天";
        }else{
            $str=date("m-d",$datetime);
        }
        return $str; //days为得到的天数;
    }

    /**
     * 查询月账单
     * @param $mhMap  条件
     * @param $limit  数目
     * @param $page   当前页
     */
    private function selectMonthMoneyList($mhMap,$pageSize,$pageIndex){

        $count = M("MoneyHistory")->where($mhMap)->order("add_time","desc")->count();
        $pages = ceil($count/$pageSize);
        $limit = ($pageIndex-1)*$pageSize;
        $monthMoneys = M("MoneyHistory")->where($mhMap)->order("add_time desc")->limit($limit.','.$pageSize)->select();//当月

        $monthMoneyList=array();
        foreach($monthMoneys as $key=>$val){
            $addTime=$val["add_time"];
            $isPlus=$val["is_plus"];
            $symbol="+";
            //是收入还是支出
            if($isPlus==0){
                $symbol="-";
            }
            $monthMoneyList[$key]["id"]=$val["id"];
            $monthMoneyList[$key]["protocol_id"]=$val["protocol_id"];
            $monthMoneyList[$key]["total"]=$symbol.$val["total"];
            $monthMoneyList[$key]["is_plus"]=$val["is_plus"];
            $monthMoneyList[$key]["date"]=$this->getDate($addTime);
            $monthMoneyList[$key]["minute"]=date("H:i",$addTime);
            $monthMoneyList[$key]["remark"]=$val["remark"];
            $monthMoneyList[$key]["order_id"]=$val["order_id"];
        }
        $data['list'] = $monthMoneyList;
        $data['pages'] = $pages;
        return $data;
    }


}